import {
	defineStore
} from 'pinia'
import pagesJson from '@/pages.json'
const uniIdCo = uniCloud.importObject("uni-id-co")
const db = uniCloud.database();
const usersTable = db.collection('uni-id-users')

let hostUserInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
let sysSetting = uni.getStorageSync('sys-setting') || {}
let loveLine = uni.getStorageSync('wolf-love-line') || []
export const useUserStore = defineStore('user', {
	state: () => ({
		userInfo: hostUserInfo,
		hasLogin: Object.keys(hostUserInfo).length != 0,
		sysSetting,
		loveLine,
	}),
	actions: {
		async init() {
			await this.updateUserInfo(),
				await this.getLoveLine()
		},
		async getLoveLine() { //获取红心关联线
			let res = await db.collection("wolf-love-line").where(`'uid' == $cloudEnv_uid`).field("hid")
				.get()
			let data = res.result.data.map(item => item.hid)
			this.loveLine = [...data]
			uni.setStorage({
				key: "wolf-love-line",
				data: this.loveLine
			})
		},
		async updateUserInfo(data = false) {
			if (data) {
				// console.log("d+++++++++",data)
				uni.showLoading({
					title: '更新中...',
					mask: true
				})
				usersTable.where('_id==$env.uid').update(data).then(e => {
					// console.log(e);
					if (e.result.updated) {
						uni.showToast({
							title: "更新成功",
							icon: 'none',
							// duration: 3000,
							mask: true,
						});
						this.setUserInfo(data)
					} else {
						uni.showToast({
							title: "没有改变",
							icon: 'none',
							// duration: 3000,
							mask: true,
						});
					}
				})

			} else {
				try {
					uni.showToast({
						title: "加载中...",
						icon: 'none',
						mask: true,
					});
					let res = await usersTable.where("'_id' == $cloudEnv_uid")
						.field(
							'mobile,nickname,username,email,avatar_file,my_invite_code,seachZstr,gender,level,money,baseInfo,gift_money,sign_score,sign_con,newLevel'
						)
						.get()
					console.log("res", res)
					this.userInfo = Object.assign({}, res.result.data[0])
					this.setUserInfo(res.result.data[0])

				} catch (e) {
					this.setUserInfo({}, {
						cover: true
					})
				}
			}
		},


		async setting() { //系统设置
			let setting = await db.collection("wolf-setting").get()
			if (setting.result.data.length > 0) {
				this.sysSetting = Object.assign({}, setting.result.data[0])
			}
			uni.setStorage({
				key: "sys-setting",
				data: this.sysSetting
			})
		},

		async logout() { //用户退出时初始化
			// 1. 已经过期就不需要调用服务端的注销接口	2.即使调用注销接口失败，不能阻塞客户端
			if (uniCloud.getCurrentUserInfo().tokenExpired > Date.now()) {
				try {
					await uniIdCo.logout()
				} catch (e) {
					console.error(e);
				}
			}
			uni.removeStorageSync('uni_id_token');
			uni.setStorageSync('uni_id_token_expired', 0)
			const page = pagesJson.pages[0]
			uni.reLaunch({
				url: `/${page.path}`
			})
			this.setUserInfo({}, {
				cover: true
			})
		},

		async setUserInfo(data, {
			cover
		} = {
			cover: false
		}) {
			let userInfo = cover ? data : Object.assign(this.userInfo, data)
			this.userInfo = Object.assign({}, userInfo)
			this.hasLogin = Object.keys(this.userInfo).length != 0
			uni.setStorage({
				key: "uni-id-pages-userInfo",
				data: this.userInfo
			})
			return data
		},
		loginBack(e = {}) {
			console.log("loginBack", e)
			const {
				uniIdRedirectUrl = ''
			} = e
			let delta = 0; //判断需要返回几层
			let pages = getCurrentPages();
			// console.log(pages);
			pages.forEach((page, index) => {
				if (pages[pages.length - index - 1].route.split('/')[3] == 'login') {
					delta++
				}
			})
			// console.log('判断需要返回几层:', delta);
			if (uniIdRedirectUrl) {
				return uni.redirectTo({
					url: uniIdRedirectUrl,
					fail: (err1) => {
						uni.switchTab({
							url: uniIdRedirectUrl,
							fail: (err2) => {
								console.log(err1, err2)
							}
						})
					}
				})
			}
			// #ifdef H5
			if (e.loginType == 'weixin') {
				// console.log('window.history', window.history);
				return window.history.go(-3)
			}
			// #endif

			if (delta) {
				const page = pagesJson.pages[0]
				return uni.reLaunch({
					url: `/${page.path}`
				})
			}

			uni.navigateBack({
				delta
			})
		},

		async loginSuccess(e = {}) {
			console.log("e++", e)
			const {
				showToast = true, toastText = '登录成功', autoBack = true, uniIdRedirectUrl = '',
					passwordConfirmed
			} = e
			await this.updateUserInfo()
			if (autoBack) {
				this.loginBack({
					uniIdRedirectUrl
				})
			}
		}
	}
})